/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { ctx2 } from '@app-cad/module';

import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useState } from 'react';
import { documentV2 } from '@app-nextmesh/domain';
import { createPoint, getNormalsOrIds, removePoint } from '../cmd-common/tools';
import {
  ChildLineCommandProps,
  circleSchema,
  circleUiSchema,
  FormType,
  Mode,
} from './type';

export const Circle = ({ onClose }: ChildLineCommandProps) => {
  const [formData, setFormData] = useState<FormType>({
    type: Mode.SELECT,
    start: null,
    second: null,
    end: null,
    startInput: null,
    secondInput: null,
    endInput: null,
  });
  const [angle, setAngle] = useState(360);

  const isFormDataValid = () => {
    if (formData.type === Mode.SELECT) {
      return (
        formData.start != null &&
        formData.end != null &&
        formData.second != null
      );
    } else {
      return (
        formData.startInput != null &&
        formData.endInput != null &&
        formData.secondInput != null
      );
    }
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }
    execute(false);
    onClose();
  };

  const execute = async (preview: boolean) => {
    if (!isFormDataValid()) {
      return;
    }
    let source = null;
    if (formData.type === Mode.SELECT) {
      const ids = getNormalsOrIds(
        [formData.start, formData.second, formData.end],
        'id',
      ).map((item) => item.id);
      source = ids;
    } else {
      source = [formData.startInput, formData.secondInput, formData.endInput];
    }
    try {
      await documentV2.basicCurve(
        { source, param: [angle], mode: 'circle' },
        preview,
      );
    } catch (error) {
      //
    }
  };

  // 释放对象
  const releaseObjects = () => {
    ctx2.cadScene.toolsGroup.clear();
  };

  const { initingEdit } = useCommand('cmd-line-between-dot', {
    releaseObjects,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  const preview = (v: FormType) => {
    const vertexs = [];
    removePoint();
    if (v.type === Mode.INPUT) {
      v?.startInput && vertexs.push(v.startInput);
      v?.secondInput && vertexs.push(v.secondInput);
      v?.endInput && vertexs.push(v.endInput);
      createPoint(vertexs);
    }
    ctx2.viewer.requestRender();
  };

  // useEffect(preview, [formData]);
  return (
    <NonDialogPickableCommandForm
      // onPreview={preview}
      className='-mt-3'
      disabled={initingEdit}
      schema={circleSchema}
      onCancel={onClose}
      formData={formData}
      onChange={(v) => {
        setAngle(v.param || 360);
        setFormData((state) => {
          if (v.type == Mode.SELECT) {
            return {
              ...v,
              startInput: v.start?.assisObj?.getVertex()?.toArray(),
              secondInput: v.second?.assisObj?.getVertex()?.toArray(),
              endInput: v.end?.assisObj?.getVertex()?.toArray(),
            };
          } else {
            preview(v);
            return {
              ...state,
              type: v.type,
              startInput: v.startInput,
              endInput: v.endInput,
            };
          }
        });
      }}
      extraUiSchema={circleUiSchema}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
